# -*- coding: utf-8 -*-
import scrapy
from pvp_qq.items import PvpQqItem


class BizhiSpider(scrapy.Spider):
    name = 'bizhi'
    allowed_domains = ['pvp.qq.com', 'pvp.qq.comherodetail', 'game.gtimg.cn']
    start_urls = ['https://pvp.qq.com/web201605/herolist.shtml']
    # 通过查找js代码发现在logic.js中的sel_skin方法中找到了皮肤图片链接规则，根据皮肤的数量和英雄id来生成
    # 壁纸图片链接规则
    bizhi_url_format = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/%s/%s-bigskin-%s.jpg'

    def parse(self, response):
        uri_list = response.xpath('//ul[@class="herolist clearfix"]/li/a/@href').extract()
        for uri in uri_list:
            yield scrapy.Request(url='https://pvp.qq.com/web201605/' + uri, callback=self.detail_page)

    def detail_page(self, response):
        """
        获取到壁纸数量和英雄id
        :param response:
        :return:
        """
        # 英雄id
        user_id = response.url.split('/')[-1].split('.')[0]

        # 皮肤数量
        bizhi_num = len(response.xpath('//div[@class="pic-pf"]/ul/@data-imgname').extract_first().split('|'))
        image_urls = [self.bizhi_url_format % (user_id, user_id, x) for x in range(1, bizhi_num + 1)]
        item = PvpQqItem()
        item['image_urls'] = image_urls
        yield item


if __name__ == '__main__':
    for x in range(1, 3):
        print(x)

